package cn.wingware.util;
import java.security.MessageDigest;
public class MD5 {
	
		private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'B', 'C', 'D', 'E', 'F' };

		private static String encodingAlgorithm="MD5";
		private static String SHA1="SHA1";
		
		public final static String encoding(byte[] bs) {
			
			String encodingStr = null;
			try {
				MessageDigest mdTemp = MessageDigest.getInstance(encodingAlgorithm);
				mdTemp.update(bs);
				return toHexString( mdTemp.digest() );
				
			} catch (Exception e) {
				
			}

			return encodingStr;
		}
		
		public static String sha1(String s) {
			MessageDigest md;
			try {
				md = MessageDigest.getInstance(SHA1);
				byte[] data = s.getBytes("UTF-8");
				byte[] bytes = md.digest(data);
				return toHexString(bytes);
			}catch(Exception ex){
				ex.printStackTrace();
			}
			return null;
		}
		
		public static String toHexString(byte[] b) {  
			 StringBuilder sb = new StringBuilder(b.length * 2);  
			 for (int i = 0; i < b.length; i++) {  
			     sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);  
			     sb.append(HEX_DIGITS[b[i] & 0x0f]);  
			 }  
			 return sb.toString();  
		}
		
		public final static String encoding(String text) {
			if( text==null ){
				return null;
			}
			return encoding( text.getBytes() );
		}
		
		public final static String encodeTwice(String text) {
			if( text==null ){
				return null;
			}
			String md5Once = encoding( text.getBytes() );
			return encoding(md5Once.getBytes());
		}
		
		
}
